﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using CommunitySystem.EmpbasicService;

namespace CommunitySystem
{
    public partial class PublicOfficialSelectionWindow : ChildWindow
    {
        private PublicOfficialSelectionService.PublicOfficialSelectionServiceClient Client = new PublicOfficialSelectionService.PublicOfficialSelectionServiceClient();
        PublicOfficialSelectionService.PublicOfficialSelectionModel model = new PublicOfficialSelectionService.PublicOfficialSelectionModel();
        private EmpbasicService.EmpBasicServiceClient Client2 = new EmpbasicService.EmpBasicServiceClient();
        public ObservableCollection<BianZhiModel> BianZhiModels = new ObservableCollection<BianZhiModel>();
        public ObservableCollection<BianZhiModel> SelectedModels = new ObservableCollection<BianZhiModel>();
        public int ID;
        //public int OrgID;
        public List<string> orgids = new List<string>();
        public bool IsNew = false;
        public string isLock = "";
        private int ExamID = 0;
        private int KaoShiType = 0;
        public PublicOfficialSelectionWindow(List<string> orgID, bool isnew, int iD,string chakan,string islocked,int examid,int kaoshitype)
        {
            InitializeComponent();
            orgids = orgID;
            ID = iD;
            IsNew = isnew;
            isLock = islocked;
            ExamID = examid;
            KaoShiType = kaoshitype;
            orgid.OnSelectionChanged += new OnSelectionChangedEvent(orgid_OnSelectionChanged);
            //DutyLevel.OnSelectionChanged += new OnSelectionChangedEvent(DutyLevel_OnSelectionChanged);
            //DutyAttribute.OnSelectionChanged += new OnSelectionChangedEvent(DutyAttribute_OnSelectionChanged);
            Client2.GetBianZhiModelCompleted += new EventHandler<EmpbasicService.GetBianZhiModelCompletedEventArgs>(Client_GetBianZhiModelCompleted);
            Client2.GetBianZhiDetailModelCompleted += new EventHandler<GetBianZhiDetailModelCompletedEventArgs>(Client2_GetBianZhiDetailModelCompleted);
            if(KaoShiType == 0)
            {
                jzxxb.IsChecked = true;
                xdjl.IsChecked = false;
            }
            else
            {
                jzxxb.IsChecked = false;
                xdjl.IsChecked = true;
            }
            if (orgids[0] == "0")
            {
                tiaojian.Visibility = System.Windows.Visibility.Collapsed;
                orgid.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                tiaojian.Visibility = System.Windows.Visibility.Visible;
                orgid.Visibility = System.Windows.Visibility.Collapsed;
                //Client.GetOrgNamebyOrgIDCompleted += new EventHandler<PublicOfficialSelectionService.GetOrgNamebyOrgIDCompletedEventArgs>(Client_GetOrgNamebyOrgIDCompleted);
                //Client.GetOrgNamebyOrgIDAsync(OrgID);
                string ord = "";
                foreach(string i in orgids)
                {
                    ord = ord + i + ",";
                }
                Client2.GetOrgForHRModelbyIDsCompleted += new EventHandler<EmpbasicService.GetOrgForHRModelbyIDsCompletedEventArgs>(Client2_GetOrgForHRModelbyIDsCompleted);
                Client2.GetOrgForHRModelbyIDsAsync("(" + ord.Substring(0, ord.Length - 1) + ")");
            }
            if (IsNew)
            {
                this.Title = "新增职位信息";
                model = new PublicOfficialSelectionService.PublicOfficialSelectionModel();
                model.OrgID = Convert.ToInt32(orgids[0]);
                orgid.Field = "OrgID";
                model.IsLocked = false;
                model.ExameID = ExamID;
                //if (orgids != null && orgids.Count > 0) Client2.GetBianZhiModelAsync(orgids[0].ToString(), 0);
                this.DataContext = model;
            }
            else
            {
                this.Title = "编辑职位信息";
                if (orgids[0] != "0")
                {
                    model.OrgID = Convert.ToInt32(orgids[0]);
                    orgid.Field = "OrgID";
                    Client2.GetBianZhiModelAsync(model.OrgID.ToString(), 0);
                }
                
                Client.GetPublicOfficialSelectionCompleted += new EventHandler<PublicOfficialSelectionService.GetPublicOfficialSelectionCompletedEventArgs>(Client_GetPublicOfficialSelectionCompleted);
                Client.GetPublicOfficialSelectionAsync("0", ID, 0, 20, -1, DateTime.Today.Year, isLock,ExamID);
            }
            if(chakan == "查看")
            {
                tiaojian.IsEnabled =
                    orgid.IsEnabled =
                    zhiwei.IsEnabled = renshu.IsEnabled = zhiweijianjie.IsEnabled = wenhuachengdu.IsEnabled =
                                                                                    zhengzhimianmao.IsEnabled =
                                                                                    zige.IsEnabled =
                                                                                    beizhu.IsEnabled =DutyAttribute.IsEnabled = DutyLevel.IsEnabled=
                                                                                    biaoti.IsEnabled= false;
                OKButton.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                tiaojian.IsEnabled =
                    orgid.IsEnabled =
                    zhiwei.IsEnabled = renshu.IsEnabled = zhiweijianjie.IsEnabled = wenhuachengdu.IsEnabled =
                                                                                    zhengzhimianmao.IsEnabled =
                                                                                    zige.IsEnabled =
                                                                                    beizhu.IsEnabled = DutyAttribute.IsEnabled = DutyLevel.IsEnabled =
                                                                                     biaoti.IsEnabled = true;
                OKButton.Visibility = System.Windows.Visibility.Visible;
            }
        }
        private string pattern = @"^[0-9]+([.]{1}[0-9]+){0,1}$";
        private void TextBox_LostFocus1(object sender, RoutedEventArgs e)
        {
            Match m = Regex.Match(((TextBox)sender).Text, pattern); // 匹配正则表达式
            if (!m.Success) // 输入的不是数字
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("只能输入数字！");
                ((TextBox)sender).Text = "";
                return;
            }
        }
        void Client2_GetBianZhiDetailModelCompleted(object sender, GetBianZhiDetailModelCompletedEventArgs e)
        {
            SelectedModels.Clear();
            BianZhiModels = e.Result;
            if (BianZhiModels != null && BianZhiModels.Count > 0)
            {
                //string zhurenkeyong = "";
                //int i1 =
                //    Convert.ToInt32(
                //        !string.IsNullOrEmpty(BianZhiModels.OrderBy(p => p.FuKeLingDao).FirstOrDefault().FuKeLingDao)
                //            ? BianZhiModels.OrderBy(p => p.FuKeLingDao).FirstOrDefault().FuKeLingDao
                //            : "0");
                //int i2 =
                //    Convert.ToInt32(
                //        !string.IsNullOrEmpty(
                //            BianZhiModels.OrderByDescending(p => p.zhurenshiyou).FirstOrDefault().zhurenshiyou)
                //            ? BianZhiModels.OrderByDescending(p => p.zhurenshiyou).FirstOrDefault().zhurenshiyou
                //            : "0");

                //int i3 = 0;
                //foreach (BianZhiModel b in BianZhiModels)
                //{
                //    if (!string.IsNullOrEmpty(b.ZhuRenJieYongQingKuang) && b.ZhuRenJieYongQingKuang != "无")
                //    {
                //        if (Math.Abs(Convert.ToInt32(b.ZhuRenJieYongQingKuang)) > i3)
                //            i3 = Convert.ToInt32(b.ZhuRenJieYongQingKuang);
                //    }
                //}
                //int i4 =
                //    Convert.ToInt32(
                //        BianZhiModels.OrderByDescending(p => p.ZhuRenChaoZhiQingKuang).FirstOrDefault().
                //            ZhuRenChaoZhiQingKuang == "无"
                //            ? "0"
                //            : BianZhiModels.OrderByDescending(p => p.ZhuRenChaoZhiQingKuang).FirstOrDefault().
                //                  ZhuRenChaoZhiQingKuang);
                //zhurenkeyong = "统筹：" + (i1 - i2 + i3 + i4).ToString();

                //string fuzhurenkeyong = "";
                //int f1 =
                //    Convert.ToInt32(
                //        !string.IsNullOrEmpty(BianZhiModels.OrderBy(p => p.FuKeFeiLingDao).FirstOrDefault().FuKeFeiLingDao)
                //            ? BianZhiModels.OrderBy(p => p.FuKeFeiLingDao).FirstOrDefault().FuKeFeiLingDao
                //            : "0");
                //int f2 =
                //    Convert.ToInt32(
                //        !string.IsNullOrEmpty(
                //            BianZhiModels.OrderByDescending(p => p.fuzhurenshiyou).FirstOrDefault().fuzhurenshiyou)
                //            ? BianZhiModels.OrderByDescending(p => p.fuzhurenshiyou).FirstOrDefault().fuzhurenshiyou
                //            : "0");

                //int f3 = 0;
                //foreach (BianZhiModel b in BianZhiModels)
                //{
                //    if (!string.IsNullOrEmpty(b.FuZhuRenJieYongQingKuang) && b.FuZhuRenJieYongQingKuang != "无")
                //    {
                //        if (Math.Abs(Convert.ToInt32(b.FuZhuRenJieYongQingKuang)) > f3)
                //            f3 = Convert.ToInt32(b.FuZhuRenJieYongQingKuang);
                //    }
                //}
                //int f4 =
                //    Convert.ToInt32(
                //        BianZhiModels.OrderByDescending(p => p.FuZhuRenChaoZhiQingKuang).FirstOrDefault().
                //            FuZhuRenChaoZhiQingKuang == "无"
                //            ? "0"
                //            : BianZhiModels.OrderByDescending(p => p.FuZhuRenChaoZhiQingKuang).FirstOrDefault().
                //                  FuZhuRenChaoZhiQingKuang);
                //fuzhurenkeyong = "统筹：" + (f1 - f2 + f3 + f4).ToString();

                //if (BianZhiModels.Where(p => p.ZhengKeLingDaoTC == true).Count() > 0)
                //{
                //    foreach (BianZhiModel i in BianZhiModels.Where(p => p.ZhengKeLingDaoTC == true))
                //    {
                //        int zhiwhu = !string.IsNullOrEmpty(i.ZhengKeLingDao) ? Convert.ToInt32(i.ZhengKeLingDao) : 0;
                //        int renshu = BianZhiModels.Where(p => p.ZhengKeLingDaoTC == true).Sum(
                //            p => !string.IsNullOrEmpty(p.zhengkeshiyou) ? Convert.ToInt32(p.zhengkeshiyou) : 0);
                //        int jieyong = BianZhiModels.Where(p => p.ZhengKeLingDaoTC == true).Sum(
                //            p =>
                //            p.ZhengKeJieYongQingKuang != "无" ? Convert.ToInt32(p.ZhengKeJieYongQingKuang) : 0);
                //        int chaozhi = BianZhiModels.Where(p => p.ZhengKeLingDaoTC == true).Sum(
                //            p =>
                //            p.ZhengKeChaoZhiQingKuang != "无" ? Convert.ToInt32(p.ZhengKeChaoZhiQingKuang) : 0);

                //        i.ZhengKeShiJi =
                //            (zhiwhu - renshu + jieyong + chaozhi)
                //                .ToString();
                //        //i.ZhengKeShiJi =
                //        //    (Convert.ToInt32(
                //        //        BianZhiModels.Where(p => p.ZhengKeLingDaoTC == true).OrderBy(p => p.ZhengKeShiJi).
                //        //            FirstOrDefault().ZhengKeShiJi) +
                //        //     BianZhiModels.Sum(
                //        //         p => p.ZhengKeJieYongQingKuang != "无" ? Convert.ToInt32(p.ZhengKeJieYongQingKuang) : 0) +
                //        //     BianZhiModels.Sum(
                //        //         p => p.ZhengKeChaoZhiQingKuang != "无" ? Convert.ToInt32(p.ZhengKeChaoZhiQingKuang) : 0))
                //        //        .ToString();
                //    }
                //}

                //if (BianZhiModels.Where(p => p.ZhengKeFeiLingDaoTC == true).Count() > 0)
                //{
                //    //foreach (BianZhiModel i in BianZhiModels.Where(p => p.ZhengKeFeiLingDaoTC == true))
                //    //{
                //    //    i.FuKeShiJi =
                //    //        BianZhiModels.Where(p => p.ZhengKeFeiLingDaoTC == true).OrderBy(p => p.FuKeShiJi).
                //    //            FirstOrDefault().FuKeShiJi;
                //    //}
                //    foreach (BianZhiModel i in BianZhiModels.Where(p => p.ZhengKeFeiLingDaoTC == true))
                //    {
                //        i.FuKeShiJi =
                //            (Convert.ToInt32(
                //                BianZhiModels.Where(p => p.ZhengKeFeiLingDaoTC == true).OrderBy(p => p.FuKeShiJi).
                //                    FirstOrDefault().FuKeShiJi) +
                //             BianZhiModels.Sum(
                //                 p => p.FuKeJieYongQingKuang != "无" ? Convert.ToInt32(p.FuKeJieYongQingKuang) : 0) +
                //             BianZhiModels.Sum(
                //                 p => p.FuKeChaoZhiQingKuang != "无" ? Convert.ToInt32(p.FuKeChaoZhiQingKuang) : 0))
                //                .ToString();

                //        int zhiwhu = !string.IsNullOrEmpty(i.ZhengKeFeiLingDao) ? Convert.ToInt32(i.ZhengKeFeiLingDao) : 0;
                //        int renshu = BianZhiModels.Where(p => p.ZhengKeFeiLingDaoTC == true).Sum(
                //            p => !string.IsNullOrEmpty(p.fukeshiyou) ? Convert.ToInt32(p.fukeshiyou) : 0);
                //        int jieyong = BianZhiModels.Where(p => p.ZhengKeFeiLingDaoTC == true).Sum(
                //            p =>
                //            p.FuKeJieYongQingKuang != "无" ? Convert.ToInt32(p.FuKeJieYongQingKuang) : 0);
                //        int chaozhi = BianZhiModels.Where(p => p.ZhengKeFeiLingDaoTC == true).Sum(
                //            p =>
                //            p.FuKeChaoZhiQingKuang != "无" ? Convert.ToInt32(p.FuKeChaoZhiQingKuang) : 0);

                //        i.ZhengKeShiJi =
                //            (zhiwhu - renshu + jieyong + chaozhi)
                //                .ToString();
                //    }
                //}
                //if(model.DutyLevel == "乡科级正职（主任科员）" && model.DutyAttribute == "领导职务")
                //{
                //    foreach (BianZhiModel i in BianZhiModels.Where(p=>p.JiGouMingCheng != "合计"))
                //    {
                //        if (Convert.ToInt32(i.ZhengKeShiJi) > 0)
                //            SelectedModels.Add(i);

                //    }
                //}
                biaoti.ItemsSource = e.Result;
                if (biaoti.ItemsSource != null)
                {
                    for (int i = 0; i < ((ObservableCollection<BianZhiModel>)biaoti.ItemsSource).Count; i++)
                    {
                        if (((ObservableCollection<BianZhiModel>)biaoti.ItemsSource)[i].JiGouMingCheng == model.Department_Duty)
                            biaoti.SelectedIndex = i;
                    }
                }
            }
        }

        void Client_GetBianZhiModelCompleted(object sender, EmpbasicService.GetBianZhiModelCompletedEventArgs e)
        {
            biaoti.ItemsSource = null;
            biaoti.ItemsSource = e.Result;
            if (biaoti.ItemsSource != null)
            {
                for (int i = 0; i < ((ObservableCollection<BianZhiModel>)biaoti.ItemsSource).Count; i++)
                {
                    if (((ObservableCollection<BianZhiModel>)biaoti.ItemsSource)[i].JiGouMingCheng == model.Department_Duty)
                        biaoti.SelectedIndex = i;
                }
            }
        }

        private int keyongzhishu = 0;
        void gangwei_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((ComboBox)sender).SelectedItem != null)
            {
                model.Department_Duty = ((BianZhiModel)((((ComboBox)sender).SelectedItem))).JiGouMingCheng;
                if (model.DutyLevel == "乡科级正职（主任科员）" && model.DutyAttribute == "领导职务")
                    keyongzhishu = Convert.ToInt32(((BianZhiModel) ((((ComboBox) sender).SelectedItem))).ZhengKeShiJi);
                if (model.DutyLevel == "乡科级正职（主任科员）" && model.DutyAttribute == "非领导职务")
                    keyongzhishu = Convert.ToInt32(((BianZhiModel)((((ComboBox)sender).SelectedItem))).ZhuRenShiJi);
                if (model.DutyLevel == "乡科级副职（副主任科员）" && model.DutyAttribute == "领导职务")
                    keyongzhishu = Convert.ToInt32(((BianZhiModel)((((ComboBox)sender).SelectedItem))).FuKeShiJi);
                if (model.DutyLevel == "乡科级副职（副主任科员）" && model.DutyAttribute == "非领导职务")
                    keyongzhishu = Convert.ToInt32(((BianZhiModel)((((ComboBox)sender).SelectedItem))).FuZhuRenShiJi);
            }

        }

        void DutyAttribute_OnSelectionChanged(object sender, object NewValue, object OldValue)
        {
            if (NewValue != null)
            {
                model.DutyAttribute = NewValue.ToString();
                if (model.OrgID != 0 && !string.IsNullOrEmpty(model.DutyLevel))
                    Client2.GetBianZhiDetailModelAsync(model.OrgID.ToString(),"");
            }
        }

        void DutyLevel_OnSelectionChanged(object sender, object NewValue, object OldValue)
        {
            if (NewValue != null)
            {
                model.DutyLevel = NewValue.ToString();
                if (!string.IsNullOrEmpty(model.DutyAttribute) && model.OrgID != 0)
                    Client2.GetBianZhiDetailModelAsync(model.OrgID.ToString(), "");
            }
        }

        void orgid_OnSelectionChanged(object sender, object NewValue, object OldValue)
        {
            if(NewValue != null)
            {
                model.OrgID = Convert.ToInt32(NewValue.ToString());
                Client2.GetBianZhiModelAsync(NewValue.ToString(), 0);
                //if(!string.IsNullOrEmpty(model.DutyAttribute) && !string.IsNullOrEmpty(model.DutyLevel))
                //     Client2.GetBianZhiDetailModelAsync(model.OrgID.ToString());
            }
        }

        void Client2_GetOrgForHRModelbyIDsCompleted(object sender, EmpbasicService.GetOrgForHRModelbyIDsCompletedEventArgs e)
        {
            tiaojian.ItemsSource = e.Result;
            for (int i = 0; i < tiaojian.Items.Count; i++)
            {
                if (((OrgForHRModel)(tiaojian.Items[i])).ID
                    == model.OrgID)
                {
                    tiaojian.SelectedIndex = i;
                }
            }
        }

        private void tiaojian_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((ComboBox)sender).SelectedItem != null)
            {
                model.OrgID = Convert.ToInt32(((OrgForHRModel)((((ComboBox)sender).SelectedItem))).ID);
                Client2.GetBianZhiModelAsync(model.OrgID.ToString(), 0);
            }
        }

        void Client_GetOrgNamebyOrgIDCompleted(object sender, PublicOfficialSelectionService.GetOrgNamebyOrgIDCompletedEventArgs e)
        {
            //feiadmin.Text = e.Result;
        }

        void Client_GetPublicOfficialSelectionCompleted(object sender, PublicOfficialSelectionService.GetPublicOfficialSelectionCompletedEventArgs e)
        {
            if (e.Result != null)
                model = e.Result[0];
            if (model.IsJZXXB == true) jzxxb.IsChecked = true;
            if (model.IsXDJL == true) xdjl.IsChecked = true;
            Client2.GetBianZhiModelAsync(model.OrgID.ToString(), 0);
            this.DataContext = model;
        }
        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }
        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            if (xdjl.IsChecked == true) model.IsXDJL = true; else model.IsXDJL = false;
            if (jzxxb.IsChecked == true) model.IsJZXXB = true; else model.IsJZXXB = false;
            if (model.OrgID == 0)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请选择用人部门！");
                return;
            }
            if (tiaojian.Visibility == System.Windows.Visibility.Visible) model.OrgID = Convert.ToInt32(((CommunitySystem.EmpbasicService.OrgForHRModel)(tiaojian.SelectedItem)).ID);
            model.Department = "徐汇区";
            if (!string.IsNullOrEmpty(model.PeopleCount))
            {
                if (keyongzhishu - Convert.ToInt32(model.PeopleCount) < 0) model.CheckMemo = "需求数大于实际职数";
                if (keyongzhishu - Convert.ToInt32(model.PeopleCount) > 0) model.CheckMemo = "可用";
                if (keyongzhishu - Convert.ToInt32(model.PeopleCount) == 0) model.CheckMemo = "无职数";
            }
            if (IsNew == true)
            {
                model.ExameID = ExamID;
                model.Year = DateTime.Today.Year;
                Client.AddPublicOfficialSelectionModelCompleted += new EventHandler<PublicOfficialSelectionService.AddPublicOfficialSelectionModelCompletedEventArgs>(Client_AddPublicOfficialSelectionModelCompleted);
                Client.AddPublicOfficialSelectionModelAsync(model);
            }
            else
            {
                Client.UpdatePublicOfficialSelectionModelCompleted += new EventHandler<PublicOfficialSelectionService.UpdatePublicOfficialSelectionModelCompletedEventArgs>(Client_UpdatePublicOfficialSelectionModelCompleted);
                Client.UpdatePublicOfficialSelectionModelAsync(model);
            }
        }

        void Client_UpdatePublicOfficialSelectionModelCompleted(object sender, PublicOfficialSelectionService.UpdatePublicOfficialSelectionModelCompletedEventArgs e)
        {
            if (e.Result == true)
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("编辑成功！");
                this.DialogResult = true;
            }
        }

        void Client_AddPublicOfficialSelectionModelCompleted(object sender, PublicOfficialSelectionService.AddPublicOfficialSelectionModelCompletedEventArgs e)
        {
            if (e.Result == true)
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("新增成功！");
                this.DialogResult = true;
            }
        }

        
    }
}
